import { useQuery } from "@apollo/react-hooks";
import gql from "graphql-tag";

const AUTHORITY_FIELDS = gql`
  fragment AuthorityFields on SysAuthority {
    id
    name
    description
    level
    type
    path
    isSystem
    dateCreated
    dateUpdated
  }
  fragment AuthorityParentFields on SysAuthority {
    id
    name
    path
    description
  }
`;

export const QUERY = gql`
  query QuerySysAuthorities {
    querySysAuthorities {
      ...AuthorityFields
      children {
        ...AuthorityFields
        parent {
          ...AuthorityParentFields
        }
        children {
          ...AuthorityFields
          parent {
            ...AuthorityParentFields
          }
        }
      }
    }
  }

  ${AUTHORITY_FIELDS}
`;

export const useTable = () => {
  const { data, loading, error } = useQuery(QUERY);

  return {
    items:
      (data &&
        data.querySysAuthorities &&
        data.querySysAuthorities.map(({ children, ...rest }) => ({
          ...rest,
          children:
            (children &&
              children.length &&
              children.map(({ children, ...rest }) => ({
                ...rest,
                children:
                  (children &&
                    children.length &&
                    children.map(({ ...rest }) => ({
                      ...rest
                    }))) ||
                  null
              }))) ||
            null
        }))) ||
      [],
    loading,
    error
  };
};
